package top.mybatisx.sql.core.sql;

import top.mybatisx.sql.core.sql.base.BaseSql;
import top.mybatisx.sql.core.sql.base.OrderEnum;
import top.mybatisx.sql.core.table.QueryColumn;

/**
 * 查询
 */
public interface OrderBy<T extends BaseSql> extends BaseSql {

    // orderBy 部分的sql
    StringBuilder orderBySql = new StringBuilder();

    default T orderBy(QueryColumn... columns) {
        return this.orderByDesc(columns);
    }

    default T orderByDesc(QueryColumn... columns) {
        return this.orderBy(OrderEnum.DESC, columns);
    }

    default T orderByAsc(QueryColumn... columns) {
        return this.orderBy(OrderEnum.ASC, columns);
    }

    default T orderBy(OrderEnum orderEnum, QueryColumn... columns) {
        for (QueryColumn column : columns) {
            this.orderBy(column, orderEnum);
        }
        return (T) this;
    }

    default T orderBy(QueryColumn column, OrderEnum orderEnum) {
        orderByList.put(column, orderEnum);
        return (T) this;
    }

    default T orderBy(String sql) {
        // 加入到查询队列
        orderBySql.setLength(0);
        orderBySql.append(" order by ");
        orderBySql.append(sql);
        orderBySql.append(' ');
        return (T) this;
    }

    default String buildOrderBySql() {
        if (orderBySql.length() > 0 || orderByList.size() == 0) {
            // 如果手工设置了 sql, 直接返回
            return orderBySql.toString();
        }

        // 组装 sql
        orderBySql.setLength(0);
        orderBySql.append(" order by ");

        // 组装所有 列
        orderByList.forEach((queryColumn, orderEnum) -> {
            String tableAlias = tableAliasMap.get(queryColumn.getTable().getTableName());
            String columnSql = queryColumn.buildOrderBySql(tableAlias, orderEnum);
            orderBySql.append(columnSql);
        });

        // 去掉 列 最后的逗号
        orderBySql.deleteCharAt(orderBySql.length() - 1);
        orderBySql.append(' ');

        return orderBySql.toString();
    }
}
